import de.medieninf.ads.ADSTool;


public class Aufgabe2 {

	public static int[][] a = null;
	public static int [][] out = null;

	public static void main(String[] args) {
		int[]in = ADSTool.readPGM(args[0]);
		a = createBinaryImage(getField(in));
		int width = a[0][0];
		int height = a[0][1];
		out = new int[width][height];
		doAlgo(width,height);
		int[] pgm = getArray(out,in);
		ADSTool.savePGM("out.pgm", pgm);

	}
	private static boolean checkPixel(int a){
		if(a > 0)
			return true;
		else
			return false;
	}
	
	private static int setPixel(int a,int count){
		return checkPixel(a) ? count:0;
	}
	private static void setPixel2(int x, int y, int count){
		a[x][y] = count;
	}
	private static int[][] createBinaryImage(int[][] a){
		int count = 1;
		for(int i = 3; i < a[0][0]; i++)
			for(int j=0; j < a[0][1]; j++)
				a[i][j] = setPixel(a[i][j],count);
		return a;
	}
	private static int getPixel(int x, int y){
		return a[x][y];
	}
	private static void findRegion(int x,int y,int count,int width,int height){
		if((x < 0) || (x >= width)) return;
		if((y < 0) || (y >= height))return;
		if(getPixel(x,y) == 1){
			setPixel2(x,y,count);
			findRegion(x,y+1,count,width,height);
			findRegion(x-1,y,count,width,height);
			findRegion(x,y-1,count,width,height);
			findRegion(x+1,y,count,width,height);
		}
	}
	private static void doAlgo(int width, int height){
		int count = 1;
		for(int i=0; i < height-1; i++ )
			for(int j=0; i < width-1; j++)
				findRegion(i,j,count,width,height);
		count++;
	}
	public static int[][] getField(int[] sourceImage) {

        // Create a new to-dimensional field with the size of the source image
        int[][] returnField = new int[sourceImage[1]][sourceImage[0]];

        // Set the counter to 3, to ignore the default values at the beginning
        // of the image-array (height, etc.)
        int sourceCounter = 3;

        // Write the image-file values to the two-dimensional array
        for (int i = 0; i < sourceImage[1]; i++) {
                for (int j = 0; j < sourceImage[0]; j++) {

                        returnField[i][j] = sourceImage[sourceCounter];
                        sourceCounter++;
                }
        }

        return returnField;

	}
	public static int[]getArray(int[][]targetField,int[]sourceImage) {

        //Create a new array with the length of the original image-file
        int [] returnField = new int [(sourceImage[0]*sourceImage[1])+3];
        int p = 0;

        //Copy every image-value to the new image-file
                for(int i = 0;i<sourceImage[0];i++) {   
                        for(int j = 0;j<sourceImage[1];j++) {
                                returnField[p] = targetField[i][j];
                                p++;
                        }
                }

        return returnField;
        
	}


}
